package com.baseframe.tool.utils.data;

import cn.hutool.core.lang.tree.Node;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 树结构
 * @param <T>
 */
@Data
public class Tree<T extends Tree.Node<T>> {


    private List<T> nodes;

    public Tree(List<T> nodes){

        this.nodes = warpTree(nodes);
    }



    public static<T extends Node<T>> Tree<T> init(List<T> nodes){

        return new Tree<>(nodes);
    }


    @Data
    @EqualsAndHashCode
    @ToString
    public static class Node<T>{

        private Long id;
        private Long parent;
        private List<T> childNode;
        private Integer sort;

    }

    @SuppressWarnings("all")
    private static<T extends Node<T>>  void wrapNode(Collection<T> nodes){


        for (T node : nodes) {
            List<T> childList = nodes
                    .stream()
                    .filter(e -> Objects.equals(e.getParent(), node.getId()))//获取当前节点的子节点
                    .sorted(Comparator.comparing(Node::getSort))
                    .collect(Collectors.toList()
                    );

            node.setChildNode(childList);

            wrapNode(childList);
        }

    }

    /**
     * 多级树的生成方法
     * @param nodes 节点
     * @return 树形节点
     * @param <T> 树形泛型
     */
    private static <T extends Node<T>> List<T> warpTree(Collection<T> nodes){

        wrapNode(nodes);
        return nodes.stream().filter(e->e.getParent()==null).sorted(Comparator.comparing(Node::getSort)).collect(Collectors.toList());
    }


}
